import numpy as np
from scipy.fft import fft
def compute_spectrum(signal):
    """计算信号的频谱"""
    n = len(signal)
    if n == 0:
        raise ValueError("输入信号长度为0")
        
    freq = np.fft.fftfreq(n, d=1/1024)  # 采样率1024Hz
    mag = np.abs(fft(signal))
    
    # 只返回正频率部分
    pos_freq = freq[:n//2]
    pos_mag = mag[:n//2]
    
    # 添加安全检查
    max_mag = np.max(pos_mag)
    if max_mag == 0:
        return pos_freq, pos_mag
    return pos_freq, pos_mag/max_mag  # 归一化幅值